// pages/home-music/index.js
import { rankingStore,rankingNames,playerStore } from '../../store/index'

import { getSwiper , getMenuSong} from '../../service/music-api'
import getQueryRect from '../../utils/query-rect'
import throttle from '../../utils/throttle'
//使用节流函数
const throttleQueryRect = throttle(getQueryRect,1000,{trailing:true} )

Page({
  /* 页面的初始数据*/
  data: {
    playAnimState:'running',//记录图片是否旋转
    isPlaying:false, //记录歌曲是否在播放
    songPlayerInfo:{}, //正在播放歌曲的数据
    banners:[],
    swiperHeight:0,//轮播图的高度
    recommendSongs: [], //推荐歌曲
    hitMenus:[],//热门歌单
    recommendMenus:[], //推荐歌单
    summitRankings:{ 0:{}, 2:{}, 3:{} } //巅峰榜
  },
  // 搜索框的点击事件
  handleInputClick:function(){
    wx.navigateTo({
      url: '../../packageDetail/pages/detail-search/index',
    })
  },
  //点击推荐歌曲中更多跳转歌曲榜单
  handleMoreClick:function(){
    this.handleRanking("hotRanking")
  },
  //点击巅峰榜跳转到歌曲榜单
  handleRankingClick:function(event){
    //点击巅峰榜中任意一个，拿到其中的idx
    const idx = event.target.dataset.idx
    //在从ranking-store里拿到rankingNames，
    //然后在动态的根据idx从rankingNames拿到相应的名字,传入handleRanking这个函数
    const sName = rankingNames[idx]
    this.handleRanking(sName)
  },
  handleRanking:function(rName){
    //根据传入的名字，来区分是谁的歌曲榜单
    wx.navigateTo({
      url: `../../packageDetail/pages/detail-songs/index?ranking=${rName}&type=rank`,
    })
  },
  handleSongItemClick(event){
    //点击歌单获取index和歌单数据，设置在play-store
    const index = event.currentTarget.dataset.index
    playerStore.setState('playListSongs',this.data.recommendSongs)
    playerStore.setState('playListIndex',index)
  },
  //发送请求
  getHomeData:function(){
    getSwiper().then(res=>{
      this.setData({banners:res.banners})
    })
    getMenuSong().then(res=>{
      this.setData({hitMenus:res.playlists})
    })
    getMenuSong("华语").then(res=>{
      this.setData({recommendMenus:res.playlists})
    })
  },
  // 轮播图加载完图片触发的事件
  getImageLoaded:function(){
    //获取图片组件的高度给轮播图设置
    throttleQueryRect('.image').then(res=>{
    const rectHeight = res[0]
    this.setData({swiperHeight:rectHeight.height}) 
    })
  },  
  handlePauseClick(){ //点击播放暂停事件
    playerStore.dispatch('changeMusicPlayStatusAction',
                          !this.data.isPlaying)
  },
  handleInSongInfo(){//点击播放栏进入歌曲详情页
    // bug：当点击首页的播放栏的暂停按钮后也会挑战歌曲详情页
    // 解决方法：点击暂停按钮的事件使用 catch 来绑定事件
    wx.navigateTo({
      url: '../../packagePlayer/pages/music-player/index?id=' + this.data.songPlayerInfo.id,
    })
  },

//=================    监听        ==================
  setupPlayerStoreListener:function(){
    // 监听播放事件
    playerStore.onStates(["songPlayerInfo", "isPlaying"], ({songPlayerInfo, isPlaying}) => {
      if (songPlayerInfo) this.setData({songPlayerInfo })
      if (isPlaying !== undefined) {
        this.setData({ 
          isPlaying,
          playAnimState: isPlaying? "running": "paused" 
        })
      }
    })


   //获取推荐歌曲榜单  onState监听的意思 ，里面还要传一个回调函数
   rankingStore.onState('hotRanking',(res)=>{
     if(!res.tracks) return
     const recommendSongs = res.tracks.slice(0,6)
     this.setData({recommendSongs})
   })

   // 监听巅峰榜里新歌榜，原创榜和飙升榜里的数据
     rankingStore.onState("newRanking",this.getSummitRanking(0))
     rankingStore.onState("originalRanking",this.getSummitRanking(2))
     rankingStore.onState("upRanking",this.getSummitRanking(3))
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     this.getHomeData()

        //发起共享热歌榜数据的请求
   rankingStore.dispatch('getRankingDatas')
     
    //  从store里拿到的数据监听
    this.setupPlayerStoreListener()

    // playerStore.dispatch('getSongPlayerStore',{id:441491828})
  }, 

    //拿到巅峰榜的数据
    getSummitRanking:function(idx){
      return (res)=>{
        if(Object.keys(res).length ===0) return //如果res没有值就return
        const coverImgUrl = res.coverImgUrl
        const name = res.name
        const playCount = res.playCount
        const songList = res.tracks.slice(0,3)
        const allObj = {coverImgUrl,name,playCount,songList}
        //动态的根据id传入数据
        const sumRanking = {...this.data.summitRankings,[idx]:allObj}
        this.setData({summitRankings:sumRanking})
      }
    },
})